<?php
/**
 * Created by PhpStorm.
 * User: Qch
 * Date: 2016/9/11
 * Time: 7:40
 */

namespace Aoe\Util;

use Aoe\Attributes\Container\Dependent;
use Aoe\Util\Bus\Convertor;
use Aoe\Util\Bus\Store\Folder;
use Exception;
use Throwable;


/**
 * # 模板解析
 *  > 这个类计划是处理模板缓存功能，可以是继承或组合模板类
 *
 */
class Template
{
    protected ?Convertor $convertor = null;
    
    public function __construct(
        #[Dependent('Engine')] protected Engine $engine,
    ) {}
    
    /**
     * ## 渲染操作
     *
     * @param string $file      视图文件
     * @param array  $arguments 模板参数
     *
     * @return string | false
     */
    public function display(string $file, array $arguments = []): string | false
    {
        if (!is_file($file)) return false;
        try {
             $this->engine->display(
                 $this->get_convertor()->get($file),
                 $arguments
             );
        } catch (Throwable) {}
        
        return false;
    }
    
    public function get(int | string $key): string
    {
        try {
            return $this->engine->compile($key);
        } catch (Throwable) {
            return '';
        }
    }
    
    /**
     * @return Convertor
     * @throws Exception
     */
    protected function get_convertor(): Convertor
    {
        if (!$this->convertor) {
            $folder = Folder::getInstance();
            $this->convertor = new Convertor (
                $folder,
                $folder,
                $this->get(...),
                fn($key) => $this->temp_name($key),
                Convertor::PASS_KEY
            );
        }
        
        return $this->convertor;
    }
    
    protected function temp_name(string $name): string
    {
        return __TEMP__ . DIRECTORY_SEPARATOR . base64_encode($name);
    }
}